#include "http_server.h"
#include "http_tools.h"
#include "esp_log.h"

#define TAG "httpd.root"
#define log_e(...) ESP_LOGE(TAG, __VA_ARGS__)
#define log_i(...) ESP_LOGI(TAG, __VA_ARGS__)
#define log_w(...) ESP_LOGW(TAG, __VA_ARGS__)

extern const uint8_t cache_html_start[] asm("_binary_cache_html_start");
extern const uint8_t cache_html_end[] asm("_binary_cache_html_end");

esp_err_t root_get_handle(httpd_req_t *req)
{
    struct stat file_stat;
    http_server_t server = httpd_get_global_user_ctx(req->handle);
    if (strstr(req->uri, "index"))
    {
        strncpy(server->path, req->user_ctx, sizeof(server->path));
        sprintf(&server->path[strlen(server->path)], "/" HTTPD_INDEX_FILE_NAME);
        log_i("[/*] path : %s | url : %s", server->path, req->uri);
        if (stat(server->path, &file_stat) == -1)
        {
            log_e("Failed to stat file : %s", server->path);
            httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "File does not exist");
            return ESP_FAIL;
        }
        else
            httpd_send_file(req, server->path);
    }
    else
    {
        httpd_resp_send_chunk(req, (const char *)cache_html_start, cache_html_end - cache_html_start);
        httpd_resp_send_chunk(req, NULL, 0);
    }
    return ESP_OK;
}
